package com.zuul.zuul.filter;


import com.netflix.zuul.ZuulFilter;

import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;


@Component
public class PreZuulFilter extends ZuulFilter {


	public PreZuulFilter() {
		super();
	}

	@Override
	public String filterType() {
		/**
		 * pre :前置过滤器:请求路由之前调用。适用于身份认证的场景
		 */
		return FilterConstants.PRE_TYPE;
	}

	@Override
	public int filterOrder() {
		//数字越大优先级越低
		return 0;
	}
	@Override
	public boolean shouldFilter() {
		/**
		 *过滤设置
		 */
		return true;
	}

	@Override
	public Object run() throws ZuulException {
		System.out.println("-----------------------前置过滤器执行------------");
		RequestContext rct= RequestContext.getCurrentContext();
		HttpServletRequest request = rct.getRequest();
		System.out.println(request.getServletPath()+"-----------"+request.getRequestURL()+"=--------------------"+request.getMethod());
		if("caicai".equals(request.getParameter("username"))){
			rct.setSendZuulResponse(true);
			rct.setResponseStatusCode(200);
			rct.set("isSucess",true);//让下一个filter看
			// 到上一个filter的状态
		}else{
			rct.setResponseStatusCode(500);
			rct.setResponseBody("非法用户");
			rct.getResponse().setContentType("text/html; charset=UTF-8");
			rct.set("isSucess",false);
			rct.setSendZuulResponse(false);
			throw  new ZuulException("1",1,"200");
		}
		return null;
	}



}
